package com.vancouver.knows.ui.activity.userpost;


import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.R;
import com.vancouver.knows.business.Constants;
import com.vancouver.knows.business.bean.PostDetailInfo;
import com.vancouver.knows.business.bean.UserPostDetailInfo;
import com.vancouver.knows.business.bean.UserPostInfo;
import com.vancouver.knows.business.task.mark.FetchUserPostDetailTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteFollowTaskMark;
import com.vancouver.knows.business.task.mark.UserFollowTaskMark;
import com.vancouver.knows.ui.activity.ImageViewPagerActivity;
import com.vancouver.knows.ui.activity.citynews.CityNewsCommentsActivity;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.fragment.citydiscount.CityDiscountsView;
import com.vancouver.knows.ui.fragment.citynews.CommentItemView;
import com.vancouver.knows.util.AppUtils;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Chris Li on 2016-07-15.
 */
public class UserPostDetailActivity extends BaseActivity implements IResultReceiver, CompoundButton.OnCheckedChangeListener {

    public static final String POST_ID_EXTRA = "post_id_extra";
    public static final String PREVENT_NESTED_NAVIGATION_EXTRA = "prevent_nested_navigation_extra";
    public static final String JUMP_TYPE_EXTRA = "jump_type_extra";

    public static final String JUMP_TYPE_MY_COMMENT = "from_my_comment";

    @Bind(R.id.loadingView)
    View mLoadingView;
    @Bind(R.id.author)
    TextView mAuthor;
    @Bind(R.id.author_avatar)
    ImageView mAuthorAvatar;
    @Bind(R.id.price)
    TextView mPrice;
    @Bind(R.id.date)
    TextView mDate;
    @Bind(R.id.description)
    TextView mDescription;
    @Bind(R.id.categories)
    TextView mCategories;
    @Bind(R.id.first_image)
    ImageView mFirstImage;
    @Bind(R.id.second_image)
    ImageView mSecondImage;
    @Bind(R.id.third_image)
    ImageView mThirdImage;
    @Bind(R.id.fourth_image)
    ImageView mFourthImage;
    @Bind(R.id.fifth_image)
    ImageView mFifthImage;
    @Bind(R.id.sixth_image)
    ImageView mSixthImage;
    @Bind(R.id.seventh_image)
    ImageView mSeventhImage;
    @Bind(R.id.eighth_image)
    ImageView mEighthImage;
    @Bind(R.id.ninth_image)
    ImageView mNinthImage;
    @Bind(R.id.location_icon)
    ImageView mLocationIcon;
    @Bind(R.id.location_text)
    TextView mLocationText;
    @Bind(R.id.suggested_business_title)
    TextView mBusinessTitle;
    @Bind(R.id.hot_comment_title)
    TextView mCommentTitle;
    @Bind(R.id.content_container)
    LinearLayout mContentContainer;
    @Bind(R.id.phone)
    TextView mPhoneButton;
    @Bind(R.id.email)
    TextView mEmailButton;
    @Bind(R.id.comment)
    TextView mCommentButton;
    @Bind(R.id.like_icon)
    ToggleButton mLikeButton;
    @Bind(R.id.share_icon)
    ImageView mShareIcon;
    @Bind(R.id.report_icon)
    ImageView mReportIcon;
    @Bind(R.id.partner_text)
    TextView mPartnerText;

    private CityDiscountsView mCityDiscountsView;
    private CommentItemView mCommentItemView;

    private String mPostId;
    private String mUserId;
    private boolean mPreventNestedNavigation = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_post_detail);

        Intent intent = getIntent();
        if (intent == null) {
            return;
        }

        mPostId = intent.getStringExtra(POST_ID_EXTRA);
        if (mPostId == null) {
            return;
        }

        String jumpType = intent.getStringExtra(JUMP_TYPE_EXTRA);
        if (!StringUtil.isEmptyString(jumpType)) {
            if (jumpType.equals(JUMP_TYPE_MY_COMMENT)) {
                Intent commentsIntent = new Intent(this, CityNewsCommentsActivity.class);
                commentsIntent.putExtra("postId", mPostId);
                commentsIntent.putExtra("comment_author", intent.getStringExtra("comment_author"));
                commentsIntent.putExtra("comment_id", intent.getStringExtra("comment_id"));
                startActivity(commentsIntent);
            }
        }

        mPreventNestedNavigation = intent.getBooleanExtra(PREVENT_NESTED_NAVIGATION_EXTRA, false);

        mUserId = imContext.getSharedPrefManager().getUserId();

        ATaskMark aTaskMark = imContext.getBusinessModule().getTaskMarkPool().getFetchUserPostDetailTaskMark(mPostId);
        imContext.getBusinessModule().getServiceWrapper().fetchUserPostDetail(this, aTaskMark, mPostId, mUserId, imContext.latitude, imContext.longitude);
    }

    @Override
    protected void onResume() {
        super.onResume();

        ATaskMark aTaskMark = imContext.getBusinessModule().getTaskMarkPool().getFetchUserPostDetailTaskMark(mPostId);
        if (aTaskMark.isLoadEnd()) {
            aTaskMark.setTaskType(ATaskMark.TYPE_REFRESH);
            imContext.getBusinessModule().getServiceWrapper().fetchUserPostDetail(this, aTaskMark, mPostId, mUserId, imContext.latitude, imContext.longitude);
        }
    }

    @OnClick(R.id.back_icon)
    public void onBackButtonClicked() {
        onBackPressed();
    }

    public void onShareButtonClicked(PostDetailInfo postDetailInfo) {
        AppUtils.shareContent(this, postDetailInfo.getTitle(), postDetailInfo.getPermalink(),
                postDetailInfo.getAttachmentImage());
    }

    private void setUserPostDetailData(UserPostDetailInfo userPostDetailInfo) {

        mLoadingView.setVisibility(View.GONE);
        final PostDetailInfo postDetailInfo = userPostDetailInfo.getPostDetails();

        setActionButtons(postDetailInfo);

        Picasso.with(this)
                .load(postDetailInfo.getAuthorAvatar())
                .fit()
                .into(mAuthorAvatar);
        if (!mPreventNestedNavigation) {
            mAuthorAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(UserPostDetailActivity.this, ProfileActivity.class);
                    intent.putExtra(ProfileActivity.USER_ID_EXTRA, postDetailInfo.getAuthorId());
                    startActivity(intent);
                }
            });
        }

        mAuthor.setText(postDetailInfo.getAuthor());
        mDate.setText(getString(R.string.date_text, AppUtils.getDateStr(this, postDetailInfo.getPdg())));
        mDescription.setText(Html.fromHtml(postDetailInfo.getContent()));
        mDescription.setMovementMethod(LinkMovementMethod.getInstance());

        if (postDetailInfo.getPrice() != null) {
            mPrice.setText(getString(R.string.price, postDetailInfo.getPrice()));
        } else {
            mPrice.setVisibility(View.GONE);
        }

        String categoryText = "";
        if (postDetailInfo.getCategory() != null && postDetailInfo.getCategory().size() > 0) {
            categoryText = postDetailInfo.getCategory().get(0).getName();
        }

        if (postDetailInfo.getSubcategory() != null && postDetailInfo.getSubcategory().size() > 0) {
            categoryText += " > " + postDetailInfo.getSubcategory().get(0).getName();
        }

        if (!StringUtil.isEmptyString(categoryText)) {
            mCategories.setText(categoryText);
        }

        ArrayList<String> images = postDetailInfo.getAttachedImages();
        setPostImages(images);

        if (postDetailInfo.getCity() != null) {
            mLocationText.setText(getString(R.string.region, postDetailInfo.getCity()));
        } else {
            mLocationIcon.setVisibility(View.GONE);
            mLocationText.setVisibility(View.GONE);
        }

        if (userPostDetailInfo.getBusinessInfoList() != null && userPostDetailInfo.getBusinessInfoList().size() > 0) {
            int index = ((ViewGroup) mBusinessTitle.getParent()).indexOfChild(mBusinessTitle);
            if (mCityDiscountsView != null) {
                mContentContainer.removeView(mCityDiscountsView);
            }
            mCityDiscountsView = new CityDiscountsView(this, userPostDetailInfo.getBusinessInfoList());
            mContentContainer.addView(mCityDiscountsView, index + 1);
        } else {
            mBusinessTitle.setVisibility(View.GONE);
        }

        if (postDetailInfo.isCommentDisabled().equals("Y")) {
            mCommentTitle.setVisibility(View.GONE);
            mPartnerText.setVisibility(View.VISIBLE);
            mPartnerText.setText(Html.fromHtml(getString(R.string.partner_info, postDetailInfo.getAuthor())));
        } else {
            if (userPostDetailInfo.getCommentInfoList() != null && userPostDetailInfo.getCommentInfoList().size() > 0) {
                mCommentTitle.setVisibility(View.VISIBLE);
                if (mCommentItemView != null) {
                    mContentContainer.removeView(mCommentItemView.getCommentLayout());
                }
                mCommentItemView = new CommentItemView();
                mCommentItemView.init(this, null, userPostDetailInfo.getCommentInfoList(), mPostId);
                mContentContainer.addView(mCommentItemView.getCommentLayout());
            } else {
                mCommentTitle.setVisibility(View.GONE);
            }
        }

        setUserActionButtons(postDetailInfo);
    }

    private void setUserActionButtons(final PostDetailInfo postDetailInfo) {

        if (postDetailInfo.getPhone() == null || postDetailInfo.isContactDisabled().equals("Y")) {
            Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_phone);
            drawable.setColorFilter(ContextCompat.getColor(this, R.color.disabled_gray), PorterDuff.Mode.SRC_ATOP);
            mPhoneButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            mPhoneButton.setClickable(false);
        } else {
            Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_phone);
            drawable.clearColorFilter();
            mPhoneButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            mPhoneButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent phoneIntent = new Intent(Intent.ACTION_DIAL);
                    phoneIntent.setData(Uri.parse("tel:" + postDetailInfo.getPhone()));
                    startActivity(phoneIntent);
                }
            });
        }

        if (postDetailInfo.getEmail() == null || postDetailInfo.isContactDisabled().equals("Y")) {
            Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_email);
            drawable.setColorFilter(ContextCompat.getColor(this, R.color.disabled_gray), PorterDuff.Mode.SRC_ATOP);
            mEmailButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            mEmailButton.setClickable(false);
        } else {
            Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_email);
            drawable.clearColorFilter();
            mEmailButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            mEmailButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sendEmail(postDetailInfo);
                }
            });
        }

        if (postDetailInfo.isCommentDisabled().equals("Y")) {
            Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_comment_filled);
            drawable.setColorFilter(ContextCompat.getColor(this, R.color.disabled_gray), PorterDuff.Mode.SRC_ATOP);
            mCommentButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            mCommentButton.setClickable(false);
        } else {
            Drawable drawable = ContextCompat.getDrawable(this, R.drawable.action_comment_filled);
            drawable.clearColorFilter();
            mCommentButton.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            if (postDetailInfo.getCommentCount() > 0) {
                mCommentButton.setText(getString(R.string.comment_btn_str, postDetailInfo.getCommentCount()));
            }
            mCommentButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(UserPostDetailActivity.this, CityNewsCommentsActivity.class);
                    intent.putExtra("postId", postDetailInfo.getId());
                    startActivity(intent);
                }
            });
        }
    }

    private void setActionButtons(final PostDetailInfo postDetailInfo) {

        if (postDetailInfo.getStatus().equals(UserPostInfo.DRAFT_STATUS)) {
            mLikeButton.setVisibility(View.INVISIBLE);
            mShareIcon.setVisibility(View.INVISIBLE);
            mReportIcon.setVisibility(View.INVISIBLE);
            return;
        } else if (postDetailInfo.getStatus().equals(UserPostInfo.PUBLISH_STATUS)) {
            mLikeButton.setVisibility(View.VISIBLE);
            mShareIcon.setVisibility(View.VISIBLE);
            mReportIcon.setVisibility(View.VISIBLE);
        }

        mLikeButton.setOnCheckedChangeListener(null);
        if (postDetailInfo.getUserFollowed() == null || postDetailInfo.getUserFollowed().equals("N")) {
            mLikeButton.setChecked(false);
        } else if (postDetailInfo.getUserFollowed().equals("Y")) {
            mLikeButton.setChecked(true);
        }
        mLikeButton.setOnCheckedChangeListener(this);

        mShareIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onShareButtonClicked(postDetailInfo);
            }
        });

        mReportIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserPostDetailActivity.this, PostReportActivity.class);
                intent.putExtra(PostReportActivity.POST_ID_EXTRA, mPostId);
                startActivity(intent);
            }
        });
    }

    private void sendEmail(PostDetailInfo postDetailInfo) {
        Intent mailIntent = new Intent(Intent.ACTION_SEND);
        mailIntent.setType("text/html");
        mailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { postDetailInfo.getEmail() });
        mailIntent.putExtra(Intent.EXTRA_SUBJECT, postDetailInfo.getTitle());
        mailIntent.putExtra(Intent.EXTRA_TEXT,
                Html.fromHtml(getString(R.string.email_content, postDetailInfo.getAuthor(), postDetailInfo.getPermalink(), postDetailInfo.getTitle())));
        Intent mailer = Intent.createChooser(mailIntent, null);
        startActivity(mailer);
    }

    private void setPostImages(final ArrayList<String> images) {

        for (int i = 0; i < 9; i++) {
            if (images.size() > i) {
                ImageView imageView = null;
                switch (i) {
                    case 0:
                        imageView = mFirstImage;
                        break;

                    case 1:
                        imageView = mSecondImage;
                        break;

                    case 2:
                        imageView = mThirdImage;
                        break;

                    case 3:
                        imageView = mFourthImage;
                        break;

                    case 4:
                        imageView = mFifthImage;
                        break;

                    case 5:
                        imageView = mSixthImage;
                        break;

                    case 6:
                        imageView = mSeventhImage;
                        break;

                    case 7:
                        imageView = mEighthImage;
                        break;

                    case 8:
                        imageView = mNinthImage;
                        break;
                }

                if (imageView != null) {
                    imageView.setVisibility(View.VISIBLE);
                    Picasso.with(this).load(images.get(i)).fit().centerCrop().into(imageView);
                    final int index = i;
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(UserPostDetailActivity.this, ImageViewPagerActivity.class);
                            intent.putStringArrayListExtra("urls", images);
                            intent.putExtra("index", index);
                            startActivity(intent);
                        }
                    });
                }
            } else {
                break;
            }
        }
    }

    @Override
    public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
        if (exception == null) {
            if (taskMark instanceof FetchUserPostDetailTaskMark) {
                setUserPostDetailData(imContext.getBusinessModule().getCacheManager().getUserPostDetailInfoCache().get(mPostId));
            } else if (taskMark instanceof UserFollowTaskMark) {
                PostDetailInfo postDetailInfo = imContext.getBusinessModule().getCacheManager().getUserPostDetailInfoCache().get(mPostId).getPostDetails();
                postDetailInfo.setUserFollowed("Y");
            } else if (taskMark instanceof UserDeleteFollowTaskMark) {
                PostDetailInfo postDetailInfo = imContext.getBusinessModule().getCacheManager().getUserPostDetailInfoCache().get(mPostId).getPostDetails();
                postDetailInfo.setUserFollowed("N");
            }
        } else {
            Log.e(TAG, exception.getExMessage());
            // follow/unfollow failed, set the data back to it's original value
            if (taskMark instanceof UserFollowTaskMark) {
                PostDetailInfo postDetailInfo = imContext.getBusinessModule().getCacheManager().getUserPostDetailInfoCache().get(mPostId).getPostDetails();
                postDetailInfo.setUserFollowed("N");
            } else if (taskMark instanceof UserDeleteFollowTaskMark) {
                PostDetailInfo postDetailInfo = imContext.getBusinessModule().getCacheManager().getUserPostDetailInfoCache().get(mPostId).getPostDetails();
                postDetailInfo.setUserFollowed("Y");
            } else if (taskMark instanceof FetchUserPostDetailTaskMark) {
                if (exception.getExCode() == 1) { // post not found
                    Toast.makeText(this, exception.getExMessage(), Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    // try to show cached content if request failed.
                    if (imContext.getBusinessModule().getCacheManager().getUserPostDetailInfoCache().containsKey(mPostId)) {
                        setUserPostDetailData(imContext.getBusinessModule().getCacheManager().getUserPostDetailInfoCache().get(mPostId));
                    }
                }
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            UserFollowTaskMark userFollowTaskMark = imContext.getBusinessModule().getTaskMarkPool().getUserFollowTaskMark(mPostId);
            imContext.getBusinessModule().getServiceWrapper().userFollow(this, userFollowTaskMark, mPostId, mUserId);
        } else {
            UserDeleteFollowTaskMark userDeleteFollowTaskMark = imContext.getBusinessModule().getTaskMarkPool().getUserDeleteFollowTaskMark(mPostId);
            imContext.getBusinessModule().getServiceWrapper().userDeleteFollow(this, userDeleteFollowTaskMark, mPostId, mUserId);
        }
    }

    @Override
    public void subHandleMessage(Message msg) {
        super.subHandleMessage(msg);
        switch (msg.what) {
            case Constants.BUSINESS_STATUS_USER_COMMENT_UPVOTE:
            case Constants.BUSINESS_STATUS_USER_DELETE_COMMENT_UPVOTE:
                mCommentItemView.updateCommentLayout();
                break;
        }
    }
}
